<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/10
 * Time: 17:27
 */

namespace Upload;
use app\lib\exception\ParameterException;
use app\lib\exception\ServerException;
use think\facade\Env;

class Upload
{
    /**
     * @var $file 文件对象
     */
    private $file;
    /**
     * @var array  $config  配置项
     * path 上传目录
     * type  保存文件名的格式  date md5 sha1
     * validate array 上传规则
     */

    private $config = [
        'path' => '../public/uploads',
        'return_path' => '/uploads/',
        'rule_type' => 'date',
    ];
    /**\
     * @var array 配置简单验证规则
     */
    private $validate = [
            'size' => 500000,
            'ext'  => 'jpg,png,gif,jpeg',
    ];
    public function __construct($file)
    {
        $this->file = $file;
    }

    public function ajax_upload()
    {
        # 获取文件上传信息
        $fileName = $this->getFileName();
        # 验证 定义 转移
        $info = $this->file->validate($this->validate)
            ->rule($this->config['rule_type'])
            ->move($this->config['path']);
        if($info == false){
            throw new ParameterException([
                'msg' => '图片过大'
            ]);
        }
        return $this->returnInfo($info,$fileName);
    }

    /**
     * @return array 返回上传文件名的数组
     */
    private function getFileName()
    {
        // 获取文件信息
        $name = $this->file->getInfo('name');
        // 问件名1.jpg   所以需要转数组获取
        $fileName = explode('.',$name);
        return [
            // 文件名
            'formerlyName' => $fileName[0],
            // 保存后的文件名
            'saveName' => $fileName[0].time(),
            // 文件后缀
            'fileSuffix' => $fileName[1]
        ];
    }

    /**
     * @param $info
     * @return array 返回状态
     */
    private function returnInfo($info,$fileName)
    {
        # 组装返回的URL
        $imgName = $this->config['return_path'].$info->getSavename();
        # 斜杆转义
        $newImgName = strtr($imgName,'\\','/');
        if($info){
            return [
                'code' => 200,
                'msg' => 'succeed',
                'path' => $newImgName,
                'info' => $fileName
            ];
        }else{
            return [
                'code' => 300,
                'msg' => $info->getError(),
            ];
        }
    }
}